package org.xhl.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

/**
 * @author xhl
 * @Date 2023/12/14 14:36:31
 */
@Slf4j
public class Client2 {

    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class);
            b.handler(new LoggingHandler(LogLevel.INFO));
            b.handler(new ClientInitializer());

            ChannelFuture channelFuture = b.connect("127.0.0.1", 8888);

            Scanner scanner = new Scanner(System.in);
            final Channel[] ch = new Channel[1];
            channelFuture.addListener((ChannelFutureListener) future -> {
                ch[0] = future.channel();
            });

            ChannelFuture ff = null;
            for (; ; ) {
                String line = scanner.nextLine();
                if (line == null) {
                    break;
                }
                ff = ch[0].writeAndFlush(line + "\r\n");
                if ("bye".equalsIgnoreCase(line)) {
                    ch[0].closeFuture().sync();
                    break;
                }
            }
            if (ff != null) {
                ff.sync();
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            group.shutdownGracefully();
        }

    }
}
